// Copyright (c) 2025 Yao Yu
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

#![deny(unsafe_code)]

use core::str;
use crate::{context::Context, prelude::*};
use alloc::vec;
use ostd::mm::{FallibleVmRead, VmWriter};
use ostd::prelude::print;
use ostd::mm::VmSpace;

pub fn sys_write(fd: usize, buf_addr: *const u8, buf_len: usize, ctx: &Context) -> Result<isize> {
    match fd {
        1 => {}, // stdout
        _ => return Err(Error::new(Errno::ERESTARTSYS)),
    }
    let buf = {
        let mut buf = vec![0u8; buf_len];
        // 读取用户地址空间时，需要通过地址和长度创建一个VmReader。根据文档描述估计写入也需要创建一个VmWriter
        let user_space = ctx.user_space();
        let mut reader = user_space
        .reader(buf_addr as usize, buf_len)?;
        // 这里写入到内核空间，则创建了一个临时的VmWriter。
        reader
            .read_fallible(&mut VmWriter::from(&mut buf as &mut [u8]))
            .unwrap();
        buf
    };
    // Use the console for output safely.
    print!("{}", str::from_utf8(&buf).unwrap());
    Ok(buf_len as isize)
}